const queryString = require('querystring');
const util = require('util');
const logger = require('./logger.lib');
const ENCODING = 'utf8';

class Http {
    constructor(http = 'http') {
        this.http = require(http);
    }
    get(path, params, cb) {
        this.http.get(path + params, res => {
            res.setEncoding(ENCODING);
            var data = '';
            res.on('data', chunk => {
                data += chunk;
            })
            res.on('end', () => {
                cb.call(this, data);
            })
        }).on('error', err => {
            logger.error.error(`error:${err}`);
        })
    }
    request({ method = "GET", port, hostname, path, headers, params = {} }, cb) {
        let _params = queryString.stringify(params);
        util._extend(headers, {
            "Content-Type": "application/x-www-form-urlencoded",
            "Content-Length": Buffer.byteLength(_params),
        });

        if (method === 'GET' && _params !== '') {
            path += '?' + _params;
        }
        const req = this.http.request({ hostname, port, path, method, headers }, res => {
            res.setEncoding(ENCODING);
            var data = '';
            res.on('data', chunk => {
                data += chunk;
            });

            res.on('end', () => {
                cb.call(this, data);
            })
        })

        req.on('error', err => {
            logger.error.error(`error:${err}`);
        })
        req.write(_params);
        req.end();
    }
}

module.exports = Http;